#include "renderer_opengl.h"
#include "opengl_context_pool.h"

using namespace krryn::system;
using namespace krryn::core;

renderer_opengl::renderer_opengl(opengl_context_pool *a_Pool) : m_Pool(a_Pool), m_R(0){
	m_Count = 100;
	m_Current = m_First = glGenLists(m_Count);
}

renderer_opengl::~renderer_opengl(){
	delete m_Pool;
	m_Pool = 0;
}

void renderer_opengl::begin(){
	m_Pool->attach_context();
}

void renderer_opengl::end(){
}

void renderer_opengl::draw(){
	locker<mutex> l_Section(m_Guard);
	m_Current++;

	glNewList(m_Current, GL_COMPILE);
		glPushMatrix();
		m_R += 0.01f;
			glRotatef( m_R, 0.0f, 0.0f, 1.0f );
			glBegin( GL_TRIANGLES );
				glColor3f( 1.0f, 0.0f, 0.0f ); glVertex2f( 0.0f, 1.0f );
				glColor3f( 0.0f, 1.0f, 0.0f ); glVertex2f( 0.87f, -0.5f );
				glColor3f( 0.0f, 0.0f, 1.0f ); glVertex2f( -0.87f, -0.5f );
			glEnd();
		glPopMatrix();
	glEndList();
}

void renderer_opengl::flush(){
	clear_buffers();

	for(GLuint i = m_First; i < m_Current; i++){
		glCallList(i);
	}

	m_Current = m_First;

	glFlush();
	m_Pool->swap_buffers();
	m_Lists.clear();
}

void renderer_opengl::clear_buffers(){
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glClear(GL_COLOR_BUFFER_BIT);
}